package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.codehaus.jackson.map.ObjectMapper;

import utils.ItemsHelper;
import entities.Item;
import entities.UpdatedItem;

/**
 * Servlet implementation class ItemsServlet
 */
@WebServlet("/Items")
public class ItemsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
/**
 * static string for the field names 
 */
public static final String ITEM_ID = "itemID";
private static final String NAME = "name";
private static final String DESCRIPTION = "description";
private static final String CURRENT_BIT_AMOUNT = "currentBitAmount";
private static final String PICTURE_URL = "pictureURL";
private static final String SELL_TIMOUT = "sellTimout";
/**
 * json response field 
 */
private static final String RESULT = "result";


private static final String UPDATED_ITEMS = "updatedItems";

private static final String ITEMS_TO_UPDATE = "itemsToUpdate";




	/**
	 *return the current bit amount and winner user name (if exists) of the given item ID
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ObjectMapper mapper = new ObjectMapper();
	//	response.setContentType("text/json");
		response.setStatus(200);
		//response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
		String jspnString = (String) request.getParameter(ITEMS_TO_UPDATE);
		List<Long> itemsToUpdate = new ArrayList<Long>();
		System.out.println(this.getServletName() + ":" + jspnString);
		try {
			if(StringUtils.isNotBlank(jspnString)){
			JSONArray jsonArr = new JSONArray(jspnString);
			for(int i = 0; i < jsonArr.length(); i++ ){
				itemsToUpdate.add(jsonArr.optLong(i));
			}
			}
		} catch (JSONException e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		}
			List<UpdatedItem> updatedItems = ItemsHelper.getUpdatedItems(itemsToUpdate);
			PrintWriter writer = response.getWriter();
			writer.write(
						"{\"" + UPDATED_ITEMS +"\":" + mapper.writeValueAsString(updatedItems) + "}"					
						);
			
			writer.flush();
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean result = ItemsHelper.postItem(
				getItem(request)
				);
		response.setContentType("text/json");
		try {
			response.getWriter().write(
					new JSONObject().put(RESULT, result).toString()
					);
		} catch (JSONException e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}
	
	//gets the item from the HttpServletRequest
	private static Item getItem(HttpServletRequest request){
		JSONObject jsonObject ;
		String str = null;
		try {
			str = request.getReader().readLine();
			jsonObject = new JSONObject(str);
			return new Item(
					jsonObject.optString(NAME),
					jsonObject.optString(DESCRIPTION),
					jsonObject.optDouble(CURRENT_BIT_AMOUNT),
					jsonObject.optString(PICTURE_URL),
					jsonObject.optLong(SELL_TIMOUT)
					);
		}catch (JSONException | IOException e){
		e.printStackTrace();
		}
		return null;
	}
	

}
